﻿using System;
using System.IO;
using System.Threading;
using System.Windows.Forms;
namespace com.fukefu.Components
{
    public partial class FilePreviewForm : BaseForm
    {
        private static FilePreviewForm fp = null;
        private static Object syncObject = new Object();
        string url, bianma;
        int len;
        private FilePreviewForm()
        {
            InitializeComponent();
            this.comboBox1.SelectedIndex = 0;
        }
        public static FilePreviewForm GetInstance()
        {
            if (fp == null || fp.IsDisposed)
            {
                lock (syncObject)
                {
                    if (fp == null || fp.IsDisposed)
                    {
                        fp = new FilePreviewForm();
                    }
                }
            }
            return fp;
        }
        //选择文件
        private void button1_Click(object sender, EventArgs e)
        {
            this.button1.Enabled = false;
            FileDialog fd = new OpenFileDialog();
            fd.Filter = "所有文件(*.*)|";
            if (fd.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = fd.FileName;
            }
            this.button1.Enabled = true;
        }
        //开始
        private void button2_Click(object sender, EventArgs e)
        {
            button2.Enabled = false;
            url = textBox1.Text;
            bianma = this.comboBox1.SelectedItem.ToString();
            len = 0;
            try
            {
                len = Convert.ToInt32(this.textBox2.Text);
            }
            catch (Exception ex)
            {
                textBox3.Text = ex.Message;
            }
            new Thread(new ThreadStart(GetFileText)).Start();
        }
        //获取文件
        private void GetFileText()
        {
            if (!url.Equals("") && len != 0)
            {
                StreamReader sr = new StreamReader(url, System.Text.Encoding.GetEncoding(bianma));
                string line, result = "";
                while ((line = sr.ReadLine()) != null && len-- > 0)
                {
                    result += line + "\r\n";
                }
                sr.Close();
                SetControl("textBox3", ControlValue.Text, result);
            }
            SetControl("button2", ControlValue.Enable, true);
        }
    }
}
